package com.xkstream.client.service;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import com.google.gson.Gson;
import com.xkstream.client.R;
import com.xkstream.client.api.API;
import com.xkstream.client.application.Application;
import com.xkstream.client.entity.PushExtra;
import com.xkstream.client.http.FileUploadUtil;

import com.xkstream.client.ui.MainActivity;
import com.xkstream.client.ui.live.StartLiveActivity;
import com.xkstream.client.utils.BitmapUtil;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private final static String packageName = "com.miqtech.wymaster.wylive";
    int msgType = -1;//消息类型
    private String key;
    private PushType pt = new PushType();

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        if (LogUtil.debug) {
            LogUtil.e(TAG, "[MyReceiver]  - " + intent.getAction() + ", extras: " + printBundle(bundle));
        }
        if (bundle == null) return;
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        if (extras != null && extras.contains("online_down"))
            context.sendBroadcast(new Intent("com.yuerlive.rainbow.stoplive"));
//        String alert = bundle.getString(JPushInterface.EXTRA_ALERT);
        try {
            if (extras != null) {
                pt.setJsonObject(new JSONObject(extras));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            LogUtil.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
           /* LogUtil.e(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            Intent i = new Intent(context, LoginActivity_V2.class);
            i.setFlags(FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);*/
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            ToastUtils.show(message, 3000);

            receiveMessage(message);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            LogUtil.e(TAG, "[MyReceiver] 接收到推送下来的通知");
            CustomPushNotificationBuilder builder = new
                    CustomPushNotificationBuilder(context,
                    R.layout.layout_exception,
                    R.id.icon,
                    R.id.title,
                    R.id.text);
            // 指定定制的 Notification Layout
            builder.statusBarDrawable = R.mipmap.ic_launcher
            ;
            // 指定最顶层状态栏小图标
            builder.layoutIconDrawable = R.mipmap.ic_launcher;
            // 指定下拉状态栏时显示的通知图标
            JPushInterface.setPushNotificationBuilder(2, builder);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            //用户点击通知栏打开相应的页面
            toStartActivity(context);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            LogUtil.e(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
            // 打开一个网页等..
        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            LogUtil.e(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            LogUtil.e(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void receiveMessage(String message) {
        if (message.contains("upload")) {
            uploadLogFile();
        }
    }

    private void uploadLogFile() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Android/data/"
                + "com.xkstream.client" + File.separator + "files" + File.separator;
        File logFile = new File(path);
        if (!logFile.exists()) return;
        File[] files = logFile.listFiles();
        for (File file : files) {
            if (file.getAbsolutePath().contains("zego")
                    || file.getAbsolutePath().contains("legend_log")) {
                Map params = new HashMap<String, String>();
                Map textParams = new HashMap<String, String>();
                textParams.put("anchorId", Application.getUser().getAnchor().getAnchor_push_ur());
                Uri result = Uri.fromFile(file);
                params.put("iconFile", BitmapUtil.getPathByUri4kitkat(Application.getContext(), result));


                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        FileUploadUtil.uploadImageFile(API.FILEUPLOAD_HOST + API.UPLOAD_LOG,
                                textParams, params, null, file.getName());
                    }
                }.start();
            }

        }

    }

    private void toStartActivity(Context context) {
        Intent intent = new Intent();
        switch (isStartActivity(context, MainActivity.class)) {
            case -1:
               /* ComponentName cn = new ComponentName(packageName, packageName + ".module.main.StartActivity");
                intent.setComponent(cn);
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);*/
                break;
            case 1:
                /*intent.setClass(context, StartLiveActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
                if (pt.getJsonObject() != null) {
                    Gson g = new Gson();
                    PushExtra pushExtra = g.fromJson(pt.getJsonObject().toString(), PushExtra.class);
                    switch (pushExtra.getWycategory()) {
                        case PushExtra.KEY_LIVE:
                            intent.putExtra("category", PushExtra.KEY_LIVE);
                            intent.putExtra("id", pushExtra.getWyobject());
                            intent.putExtra("liveData", pushExtra.getLiveData());
                            break;
                        case PushExtra.KEY_VIDEO:
                            intent.putExtra("category", PushExtra.KEY_VIDEO);
                            intent.putExtra("id", pushExtra.getWyobject());
                            break;
                        case PushExtra.KEY_URL:
                            intent.putExtra("category", PushExtra.KEY_URL);
                            intent.putExtra("url", pushExtra.getWyextend());
                            break;
                        case PushExtra.KEY_NONE:
                            intent.putExtra("category", pushExtra.KEY_NONE);
                            break;
                    }
                }*/
                break;
        }
        if (intent != null && context != null) {
           // context.startActivity(intent);
        }
    }

    protected <T> int isStartActivity(Context context, Class<T> activity) {
        Intent intent = new Intent(context, activity);
        ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
        int bIsExist = -1;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            LogUtil.e(TAG, "---startAndExit---taskInfoList.size:" + taskInfoList.size());
            for (RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    bIsExist = 1;
                    break;
                }
            }
        }
        return bIsExist;
    }
}
